"""
多任务版TCP服务器

1. 循环等待接受客户端的连接请求
2. 客户端和服务端建立连接成功
    创建子线程，
    子线程设置成为守护主线程
    使用子线程专门处理客户端的请求
    避免防止主线程阻塞
"""

# 导入socket
import socket
import threading
from utils import *

BUFFER_SIZE = 2048


def handle_client(tcp_client_socket: socket.socket, tcp_client_addr: tuple):
    tcp_client_socket.send("欢迎光临【红浪漫】聊天室".encode("UTF-8"))
    thread_name = threading.current_thread().name

    while True:
        recv_data = tcp_client_socket.recv(BUFFER_SIZE)
        if not recv_data: # 如果内容为空字符串, 说明客户端断开了
            break
        # 对数据进行解码
        msg = decode_data(recv_data)
        print(msg, thread_name)

        tcp_client_socket.send("收到!\n".encode("UTF-8"))

    tcp_client_socket.close()


def main():
    # 创建socket服务器
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定ip和port
    port = 8888
    tcp_server_socket.bind(("", port))

    # 设置为被动模式，参数128表示最大客户端等待数量
    tcp_server_socket.listen(128)

    print("服务器已启动：", port)
    # 1. 循环等待接受客户端的连接请求
    while True:
        tcp_client_socket, tcp_client_addr = tcp_server_socket.accept()

        print("客户端【{}】连进来了".format(tcp_client_addr))
        thread = threading.Thread(target=handle_client, args=(tcp_client_socket, tcp_client_addr))
        thread.daemon = True # 设置为守护线程
        thread.start()

    tcp_server_socket.close()


if __name__ == '__main__':
    main()
